package com.atguigu.spring5_webflux.service.impl;

import com.atguigu.spring5_webflux.entity.User;
import com.atguigu.spring5_webflux.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    // 模拟dao层，创建map集合存储演示数据
    private final Map<Integer,User> users = new HashMap<>();

    public UserServiceImpl() {
        // bean实例化时，利用构造器，初始化数据
        this.users.put(1,new User("one","boy",10));
        this.users.put(2,new User("two","girl",10));
        this.users.put(3,new User("three","boy",10));
    }

    @Override
    public Mono<User> getUserById(int id) {
        users.get(id);
        return Mono.justOrEmpty(this.users.get(id));
    }

    @Override
    public Flux<User> getAllUser() {
        return Flux.fromIterable(this.users.values());
    }

    @Override
    public Mono<Void> saveUserInfo(Mono<User> userMono) {
        return userMono.doOnNext(person ->{
            // 向map中放值
            int id = users.size()+1;
            users.put(id,person);
        }).thenEmpty(Mono.empty());
    }
}
